/*
 * Created on 2006-3-18
 * Last modified on 2006-3-18
 * Powered by YeQiangWei.com
 */

package com.yeqiangwei.util;

public class IpUtils{
	
	public static void main(String args[]){
		System.out.println(IpUtils.enAddr("192.168.1.1"));
		
	}
    
    public static long enIpAddr(String ip){
    	long l = 0;
    	ip = enAddr(ip); 
    	l = TypeChange.stringToLong(ip);
    	return l;
    }
    
    
    public static long deIpAddr(String ip){
    	long l = 0;
    	ip = deAddr(ip); 
    	l = TypeChange.stringToLong(ip);
    	return l;
    }
    
    public static String enAddr(String ip){
        if(Validator.isEmpty(ip)){
        	ip = "127.0.0.1";
        }
        String esip, str1, str2, str3, str4;
        long int1, int2, int3, int4;
        int i = ip.indexOf("."); //取小数点第一次出现的位置
        str1 = ip.substring(0,i); //截取字符串指定长度substring 相当于vb的Mid函数。
        // 分别取出Ip各段字符串，然后转化成Integer类型
        esip = ip.substring(i+1);
        i = esip.indexOf(".");
        str2 = esip.substring(0,i);
        esip = esip.substring(i+1); //截取字符串长度从i+1到字符串尾
        i = esip.indexOf(".");
        str3 = esip.substring(0,i);  
        i = esip.indexOf(".");
        str4 = esip.substring(i+1);  
        int1 = Integer.parseInt(str1);
        int1 = Long.parseLong(str1);
        int2 = Long.parseLong(str2);
        int3 = Long.parseLong(str3);        
        int4 = Long.parseLong(str4); 
        /*
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        */
        return String.valueOf((int1 * 256 * 256 * 256) + (int2 * 256 * 256) + (int3 * 256) + int4 - 1);
    }
    
    public static String deAddr(String ip){
        if(Validator.isEmpty(ip)){
        	ip = "127.0.0.1";
        }
        long sip;
        sip = Long.parseLong(ip);
        long s1, s21, s2, s31, s3, s4;
        String temp;
        sip = sip + 1;
        s1 = sip / 256 / 256 / 256;
        s21 = s1 * 256 * 256 * 256;
        s2 = (sip - s21) / 256 / 256;
        s31 = s2 * 256 * 256 + s21;
        s3 = (sip - s31) / 256;
        s4 = sip - (s3 * 256) - s31;
        temp = String.valueOf(s1) + "." + String.valueOf(s2) + "." + String.valueOf(s3) + "." + String.valueOf(s4);
        return temp;
    }
    
    
}
